package com.ludaxu.google.holder;

import java.util.LinkedList;
import java.util.List;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.ludaxu.google.tools.UiUtils;

public class HomePictureHolder extends BaseHolder<List<String>> {
	private ViewPager viewPager;
	private List<String> datas;

	/**
	 * 当new HomePictureHolder就会调用该方法
	 */
	@Override
	public View initView() {
		viewPager = new ViewPager(UiUtils.getContext());
		return viewPager;
	}

	/**
	 * 当holder.setData才会调用
	 */
	@Override
	public void refreshView(List<String> datas) {
		this.datas = datas;
		viewPager.setAdapter(new HomeAdapter());
		viewPager.setCurrentItem(1000 * datas.size());
		viewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					runTask.stop();
					break;
				case MotionEvent.ACTION_CANCEL:
				case MotionEvent.ACTION_UP:
					runTask.start();
					break;

				default:
					break;
				}
				return false;// viewpager触摸事件,不要传递true
			}
		});
		runTask = new AuToRunTask();
		runTask.start();

	}

	boolean flag;
	private AuToRunTask runTask;

	// 与任务相关的都继承Runnable,Runnable与线程没有关系
	public class AuToRunTask implements Runnable {

		@Override
		public void run() {
			if (flag) {
				UiUtils.Cancel(this);
				int currentItem = viewPager.getCurrentItem();
				currentItem++;
				viewPager.setCurrentItem(currentItem);
				// 延迟
				UiUtils.postDelayed(this, 5000);// 递归调用
			}

		}

		public void start() {
			if (flag == false) {
				UiUtils.Cancel(this);
				flag = true;
				UiUtils.postDelayed(this, 5000);// 递归调用
			}

		}

		public void stop() {
			if (flag) {
				flag = false;
				UiUtils.Cancel(this);
			}
		}

	}

	class HomeAdapter extends PagerAdapter {
		LinkedList<ImageView> convertView = new LinkedList<ImageView>();

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		// 判断当前返回的对象和加载的view对象的关系
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ImageView view = (ImageView) object;
			convertView.add(view);// 把移除的对象添加到缓存的集合中
			container.removeView(view);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			int index = position % datas.size();
			ImageView view;
			if (convertView.size() > 0) {
				view = convertView.remove(0);
			} else {
				view = new ImageView(UiUtils.getContext());
			}

			bitmapUtils.display(view, "http://127.0.0.1:8090/image?name="
					+ datas.get(position));
			container.addView(view);// 加载的view对象
			return view;// 返回的view对象
		}

	}

}
